package hr.dario.fragments.data;



import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

public class LocListProvider extends ContentProvider{

	private DataBaseAdapter mDB;
	 
	private static final String AUTHORITY = "hr.dario.fragments.data.LocListProvider";
	public static final int LOCATIONS = 100;
	public static final int LOCATION_ID = 110;
	 
	private static final String LOCATIONS_BASE_PATH = "locations";
	public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
	        + "/" + LOCATIONS_BASE_PATH);
	 
	public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE
	        + "/mt-location";
	public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE
	        + "/mt-location";
	
	private static final UriMatcher sURIMatcher = new UriMatcher(
	        UriMatcher.NO_MATCH);
	static {
	    sURIMatcher.addURI(AUTHORITY, LOCATIONS_BASE_PATH, LOCATIONS);
	    sURIMatcher.addURI(AUTHORITY, LOCATIONS_BASE_PATH + "/#", LOCATION_ID);
	}
	
    @Override
    public boolean onCreate() {
        mDB = new DataBaseAdapter(getContext());
        return true;
    }
    
    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
        queryBuilder.setTables(DataBaseAdapter.DATABASE_TABLE_LOC);
     
        int uriType = sURIMatcher.match(uri);
        switch (uriType) {
        case LOCATION_ID:
            queryBuilder.appendWhere(DataBaseAdapter.KEY_LOC_ID + "="
                    + uri.getLastPathSegment());
            break;
        case LOCATIONS:
            // no filter
            break;
        default:
            throw new IllegalArgumentException("Unknown URI");
        }
        
        Cursor cursor = queryBuilder.query(mDB.open().mDataBase,
                projection, selection, selectionArgs, null, null, sortOrder);
        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        return cursor;
    }


	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
	    int uriType = sURIMatcher.match(uri);
	    SQLiteDatabase sqlDB = mDB.open().mDataBase;
	    int rowsAffected = 0;
	    switch (uriType) {
	    case LOCATIONS:
	        rowsAffected = sqlDB.delete(DataBaseAdapter.DATABASE_TABLE_LOC,
	                selection, selectionArgs);
	        break;
	    case LOCATION_ID:
	        String id = uri.getLastPathSegment();
	        if (TextUtils.isEmpty(selection)) {
	            rowsAffected = sqlDB.delete(DataBaseAdapter.DATABASE_TABLE_LOC,
	            		DataBaseAdapter.KEY_LOC_ID + "=" + id, null);
	        } else {
	            rowsAffected = sqlDB.delete(DataBaseAdapter.DATABASE_TABLE_LOC,
	                    selection + " and " + DataBaseAdapter.KEY_LOC_ID + "=" + id,
	                    selectionArgs);
	        }
	        break;
	    default:
	        throw new IllegalArgumentException("Unknown or Invalid URI " + uri);
	    }
	    getContext().getContentResolver().notifyChange(uri, null);
	    return rowsAffected;
	}
	
	@Override
    public String getType(Uri uri) {
        int uriType = sURIMatcher.match(uri);
        switch (uriType) {
        case LOCATIONS:
            return CONTENT_TYPE;
        case LOCATION_ID:
            return CONTENT_ITEM_TYPE;
        default:
            return null;
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        int uriType = sURIMatcher.match(uri);
        if (uriType != LOCATIONS) {
            throw new IllegalArgumentException("Invalid URI for insert");
        }
        SQLiteDatabase sqlDB = mDB.open().mDataBase;
        long newID = sqlDB
                .insert(DataBaseAdapter.DATABASE_TABLE_LOC, null, values);
        if (newID > 0) {
            Uri newUri = ContentUris.withAppendedId(uri, newID);
            getContext().getContentResolver().notifyChange(uri, null);
            return newUri;
        } else {
            throw new SQLException("Failed to insert row into " + uri);
        }
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        int uriType = sURIMatcher.match(uri);
        SQLiteDatabase sqlDB = mDB.open().mDataBase;

        int rowsAffected;

        switch (uriType) {
        case LOCATION_ID:
            String id = uri.getLastPathSegment();
            StringBuilder modSelection = new StringBuilder(DataBaseAdapter.KEY_LOC_ID
                    + "=" + id);

            if (!TextUtils.isEmpty(selection)) {
                modSelection.append(" AND " + selection);
            }

            rowsAffected = sqlDB.update(DataBaseAdapter.DATABASE_TABLE_LOC,
                    values, modSelection.toString(), null);
            break;
        case LOCATIONS:
            rowsAffected = sqlDB.update(DataBaseAdapter.DATABASE_TABLE_LOC,
                    values, selection, selectionArgs);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI");
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return rowsAffected;
    }
}
